import { getErrorMessage } from "../error";
function nilV(o: any) {
    return typeof o === "undefined" || o === null;
}

function toString(o: any) {
    if (nilV(o)) {
        return "";
    }
    if (typeof o === "object") {
        let str = "";
        try {
            str = JSON.stringify(o);
        } catch (err) {
            str = getErrorMessage(err) || "";
        }
        return str;
    }
    return `${o}`;
}

function toObj(o: any): { [k: string]: any } | null {
    if (nilV(o)) {
        return null;
    }
    if (typeof o === "object") {
        return o;
    }
    if (typeof o === "string") {
        let res: { [k: string]: any } | null = null;
        try {
            res = JSON.parse(o);
        } catch (err) {}
        return res;
    }
    return null;
}

function delay(t: number): Promise<void> {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve();
        }, t);
    });
}
function emptyValue(o: any) {
    let v = nilV(o);
    if (v) {
        return true;
    }
    if (typeof o === "string") {
        return o.trim().length === 0;
    } else if (Array.isArray(o)) {
        return o.length === 0;
    } else if (typeof o === "number") {
        return false;
    } else if (typeof o === "object") {
        return Object.keys(o).length === 0;
    }
    return false;
}

// 获取 number
function getNumberValue(n: any) {
    let num = Number.NaN;
    if (typeof n === "string") {
        let str = n.trim();
        if (str.length > 0) {
            let tmp = Number(str);
            if (!Number.isNaN(tmp)) {
                num = tmp;
            }
        }
    } else if (typeof n === "number") {
        num = n;
    }
    if (Number.isNaN(num)) {
        return null;
    }
    return num;
}

// 参数校验
function objectTargetValue(o?: { [k: string]: any }, params?: string[] | string): any {
    if (nilV(o)) {
        return null;
    }
    if (typeof o !== "object") {
        return null;
    }
    // 判断参数是否都有
    let paramArr = [] as string[];
    if (typeof params === "string") {
        paramArr = [params];
    } else if (Array.isArray(params)) {
        paramArr = params;
    }

    // 检查各个参数
    for (let i = 0; i < paramArr.length; i++) {
        let p = paramArr[i];
        if (!nilV(o[p])) {
            return o[p];
        }
    }

    return null;
}

export { nilV, emptyValue, getNumberValue, objectTargetValue, delay, toString, toObj };
